<template>
    <div class="trend-detail pb-90" :class="isNight?'bg-night':'bg-white'">
        <!-- 头部 -->
        <!-- <div class="w-full h-88 flex items-center justify-between px-32 box-border">
            <div class="flex items-center w-full" @click="onRoute('/quotes?active=3')">
                <img src="@/assets/image/assets-center/convert.png" class="w-38 h-38" />
                <p class="font-38 font-600 ml-10">{{quote.name}}</p>
            </div>
            <div class="flex items-center">
                <img :src="require(`@/assets/image/icon-star${collected === '1' ? '_active': ''}.png`)"
                    class="w-30 h-30 mr-10 ml-20" @click="onCollect" />
                <img src="../../assets/image/public/record.png" alt="record-img" class="w-32 h-35 pl-30 "
                    @click="goHistory" />
            </div>
        </div> -->
        <trade-head :backFunc="() => $router.push('/')" :symbol="symbol" :islevel="true" @update-coin="onUpdate"
            @data="quote = $event" :title="$t('永续')" @changeLine="onChangeLine" :isNight="isNight" :isChange="isChange" :kineType="kineType"
            :tabIndex="tab" @changeNight="OnchangeNight"/>
        <div class="flex justify-between px-32 pt-40" v-if="!kineType">
            <div class="w-368 h-80 mr-32 flex justify-center items-center rounded box-border tabBtn"
                :class="tab === '1' ?'activeBtn' : ''" @click="onTab('1')">{{$t('永续合约')}}</div>
            <div class="w-368 h-80 flex justify-center items-center rounded box-border tabBtn"
                :class="tab === '2' ?'activeBtn' : ''" @click="onTab('2')">{{$t('交割合约')}}</div>
        </div>
        <!-- 数据区 -->
        <div :class="{ slide2: animated1, slide1: animated2 }">
            <div>
                <div class="flex flex-1 px-32 mt-40">
                    <div class="flex flex-col font-22">
                        <p class="font-70 font-600" :class="quote.change_ratio > 0 ? 'text-green' : 'text-red'">{{quote.close || '--'}}</p>
                        <p class="font-22 mt-10">≈ {{currency.currency_symbol}}{{ quote.close?(quote.close *
                        currency.rate).toFixed(coinLength):'--'}}
                            <span :class="quote.change_ratio > 0 ? 'text-green' : 'text-red'">{{quote.change_ratio
                            ||
                            '--'}}%</span>
                        </p>
                        <p class="text-grey mt-10">{{$t('标记价格')}} {{quote.open || '--'}}</p>
                    </div>
                    <div class="flex flex-wrap flex-1 justify-end font-22">
                        <div class="flex w-1/2 flex-col justify-between w-177">
                            <p class="text-grey">{{$t('24h最高价')}}</p>
                            <p>{{quote.high || '--'}}</p>
                        </div>
                        <div class="flex w-1/2 flex-col justify-between w-177">
                            <p class="text-grey">{{$t('24h成交量')}}({{symbol && symbol.toUpperCase() ||'--'}})</p>
                            <p>{{ fixDate(quote.amount * 1, $i18n) || '--'}}</p>
                        </div>
                        <div class="flex w-1/2 flex-col justify-between w-177 mt-20">
                            <p class="text-grey">{{$t('24h最低价')}}</p>
                            <p>{{quote.low || '--'}}</p>
                        </div>
                        <div class="flex w-1/2 flex-col justify-between w-177 mt-20">
                            <p class="text-grey">{{$t('24h成交额(USDT)')}}</p>
                            <p>{{ (quote.volume*1).toFixed(2) || '--'}}</p>
                        </div>
                    </div>
                </div>
            </div>
            <!-- k line-->
            <div class="mt-35 h-482-px">
                <kline-charts :update-key="updateKey" :update-data="quote" :isChangeLine="isChangeLine" :symbol="symbol"
                    v-if="symbol" @updataLine="isChangeLine= false"  :isNight="isNight" :isChange="isChange"/>
                    </div>
                    <div class="w-full h-20 " :class="isNight?'bg-black':'bg-grey'"></div>
            <!-- tab 区域-->
            <div class="pb-180">
                <van-tabs v-model="active">
                    <van-tab :title="$t('委托订单')" name="1" class="border-t-color">
                        <div class="flex px-32 justify-between px-32">
                            <ul class="flex flex-col flex-1 mr-20">
                                <li class="font-28 text-grey mt-30 mb-15 w-full">
                                    <p>{{$t('买入')}}</p>
                                    <p class="flex justify-between items-cener font-22">
                                        <span style="margin-right: -10px;">{{$t('价格')}}(USDT)</span>
                                        <span>{{$t('数量')}}({{ symbol.toUpperCase()}})</span>
                                    </p>
                                </li>
                                <li v-for="(item,index) in bids" :key="index" class="flex justify-between font-26 py-15"
                                    :style="{
                                                                    'background':`linear-gradient(to left,${isNight?'#1E2030':'#ffffff'} 0% ` +
                                    (item.amount / bids[bids.length - 1].amount) * 100 +'%,rgba(94,186,137,.1) ' +
                                    (item.amount / bids[bids.length - 1].amount) * 100 + '%,rgba(94,186,137,.1) 100%)'}">
                                    <span>{{item.price || '--'}}</span>
                                    <span v-if="symbol == 'shib' || symbol == 'btt'" class="text-green">{{fixDate(item.amount,$i18n) || '--'}}</span>
                                    <span v-else class="text-green">{{item.amount || '--'}}</span>
                                </li>
                            </ul>
                            <ul class="flex-1 flex flex-col ml-20">
                                <li class="font-28 text-grey mt-30 mb-15 w-full">
                                    <p>{{$t('卖出')}}</p>
                                    <p class="flex justify-between items-center font-22">
                                        <span class="-ml-5">{{$t('价格')}}(USDT)</span>
                                        <span>{{$t('数量')}}({{symbol.toUpperCase()}})</span>
                                    </p>
                                </li>
                                <li v-for="(item,index) in asks" :key="index" class="flex justify-between font-26 py-15"
                                    :style="{
                                                                        'background':`linear-gradient(to left,${isNight?'#1E2030':'#ffffff'} 0% ` +
                                    (item.amount / asks[asks.length - 1].amount) * 100 +'%,rgba(246,70,93,.1) ' +
                                    (item.amount / asks[asks.length - 1].amount) * 100 + '%,rgba(246,70,93,.1) 100%)'}">
                                    <span>{{item.price || '--'}}</span>
                                    <span v-if="symbol == 'shib' || symbol == 'btt'" class="text-red">{{fixDate(item.amount,$i18n) || '--'}}</span>
                                    <span v-else class="text-red">{{item.amount || '--'}}</span>
                                </li>
                            </ul>
                        </div>
                    </van-tab>
                    <van-tab :title="$t('最新交易')" name="2" class="border-t-color">
                        <ul class="px-32 font-28 text-grey">
                            <li class="flex justify-between mt-30">
                                <span class="flex-1">{{$t('时间')}}</span>
                                <span class="flex-1">{{$t('方向')}}</span>
                                <span class="flex-1">{{$t('价格')}}(USDT)</span>
                                <span class="flex-1 flex justify-center">{{$t('数量')}}({{symbol.toUpperCase()}})</span>
                            </li>
                            <li v-for="(item, index) in deals" :key="item.ts + item.price + item.amount || index"
                                class="flex  justify-between mt-30">
                                <span class="flex-1">{{ item.current_time ? item.current_time :'--'}}</span>
                                <span :class="item.direction === 'buy' ? 'text-green' : 'text-red'"
                                    class="flex-1">{{item.direction === 'buy' ? $t('买入') : $t('卖出') }}</span>
                                <span :class="item.direction === 'buy' ? 'text-green' : 'text-red'"
                                    class="flex-1 flex-justify-center">{{item.price || '--'}}</span>
                                <span class="flex-1 flex justify-center">{{item.amount|| '--'}}</span>
                            </li>
                        </ul>
                    </van-tab>
                    <!-- <van-tab  :title="$t('币种简介')" name="3" class="border-t-color">
                        <div class="px-20 py-20 font-40 text-grey">
                           {{  $t('关于名称',{'symbol':symbol.toUpperCase() }) }}
                        </div>
                        <div class="px-20 py-20 font-32 text-grey">
                            {{  $t(`${symbol}简介`,{'symbol':symbol.toUpperCase() }) }}
                        </div>                  
                    </van-tab> -->
                </van-tabs>
            </div>
            <!-- 按钮区 -->
            <div
                class="flex pl-40 pt-11 pb-11 pr-32 text-white justify-between  fixed bottom-108  w-full box-border h-90-px z-10 buttonSafe" 
                v-if="!kineType"
                :class="isNight?'bg-night1':'bg-grey'">
                <div class="flex flex-col mx-30 items-center" @click="onRoute('/exchangeRate')">
                    <img src="@/assets/image/icon-rate.png" class="w-38 h-38" />
                    <p class="font-25 text-grey mt-8 text-center">{{$t('汇率')}}</p>
                </div>
                <div ref="toBuy" class="w-270 h-88 bg-green flex justify-center items-center rounded-lg"
                    @click="onSubmit('buy')">
                    {{ tab == 1 ? $t('开多') : $t('买多') }}
                </div>
                <div ref="toSell" class="w-270 h-88 bg-red flex justify-center items-center rounded-lg"
                    @click="onSubmit('sell')">
                    {{ tab == 1 ?$t('开空'): $t('买空') }}</div>
            </div>
        </div>
        <van-popup v-model="show" class="rounded-2xl" :key="initFutrue.session_token">
            <popup-confirm-order :paras="initFutrue.para" :symbol="symbol" :direction="direction"
                :balance="initFutrue.amount" :price="quote.close" @close="onClose" @confirm="onOrderConfirm"
                v-if="popType === 'confirm'" />
            <popup-delivery showBtns :detailData="detailData" :key="detailData.order_no" @close="onClose"
                @continueToBuy="order()" @timeEnd="handleTimeEnd" :price="quote.close" v-else />
        </van-popup>
    </div>
</template>
<script>
import { Tab, Tabs, Popup } from 'vant';
import TradeHead from '@/components/trade-head/index.vue'
import KlineCharts from '@/components/kline-charts'
import { _getHomeList, _collect, _deleteCollect } from '@/API/home.api'
import { _getBalance, _futrueOrder, _futrueOrderInit, _futrueOrderDetail } from '@/API/trade.api'
import { mapGetters } from 'vuex';
import {fixDate} from "@/utils/utis";
import {WS_URL} from '@/config';
import PopupDelivery from "@/components/popup-delivery";
import PopupConfirmOrder from '@/components/popup-confirm-order'
export default{
    name:'TrendDetails',
    components: {
        [Tabs.name]: Tabs,
        [Tab.name]: Tab,
        [Popup.name]: Popup,
        KlineCharts,
        PopupDelivery,
        PopupConfirmOrder,
        TradeHead
    },
    data() {
        const arr = []
        for(let i = 0; i < 20; i++) {
            arr.push({
                id: i
            })
        }
        return {
            show: false,
            direction: 'buy',
            initFutrue: {},
            detailData: {},
            price: '',
            popType: 'confirm', // confirm / counting
            fixDate,
            tab: '1', // 顶部标签
            symbol: '',
            quoteData: [],
            quote: {},
            active: 1,
            asks: arr, // 卖
            bids: arr, // 买
            deals: arr, // 交易
            sockets: {
                quote: null,
                deals: null,
                askBid: null
            },
            animated1: false,
            animated2: false,
            updateKey: 1,
            collected: '0',  // 是否自选
            maxSell: 0, // 卖单最大
            maxBuy: 0, // 买单最大
            order_no: '',
            timer:null,
            isChangeLine:false,
            isNight:false,
            isChange:true, //是否有切换黑夜白天模式
            kineType:'',
            coinLength: 2
            // updateData: {}
        }
    },
    computed: {
        ...mapGetters({ currency: 'home/currency', userInfo: 'user/userInfo' })
    },
    mounted(){
        console.log('sss')
        //this.continueOrder()
        this.kineType = this.$route.query.kineType
    },
    created() {
        eventBus.$emit('onChangeNight', this.isNight);
    },
    watch: {
        active(val) { // tab切换
            if (val / 1 === 1) {
                this.sockets.deals && this.sockets.deals.close()
                this.sockets.deals = null
                if (this.symbol) { // 刚进来可能是null
                    this.startAskBidSocket()
                }
            } else {
                this.sockets.askBid && this.sockets.askBid.close()
                this.sockets.askBid = null
                this.startDealsSocket()
            }
        }
    },
    methods: {
        onChangeLine(){
            this.isChangeLine = true
        },
        continueOrder(){
            let direction = this.$route.query.direction
            if (direction) {
                this.symbol = this.$route.params.symbol
                this.tab = '2'
                console.log(this.tab)
                this.onSubmit(direction);
            }
        },
        order(){
            this.onSubmit(this.direction);
        },
        onTab(e) {
            this.tab = e
            // this.$router.go()
            if(e== 1){
                this.animated1 = true
                this.timer = setTimeout(() => {
                    this.animated1 = false
                    clearTimeout(this.timer)
                }, 200)
            }else{
                this.animated2 = true
                this.timer = setTimeout(() => {
                    this.animated2 = false
                    clearTimeout(this.timer)
                }, 200)
            }
        },
        onCollect() { // 收藏，取消收藏
            let _api = _collect
            if (this.collected === '1') {
                _api = _deleteCollect
            }
            _api(this.symbol).then(() => {
                this.collected = this.collected === '1' ? '0' : '1'
                if (this.collected === '1') {
                  this.$toast.success(this.$t('收藏成功'))
                } else {
                  this.$toast.success(this.$t('取消收藏'))
                }
            })
        },
        goHistory() {
            const url = this.topIndex / 1 === 1 ? 'perpetualHistory' : 'deliveryContractHistory'
            this.$router.push({
                path: `/${url}?symbol=${this.symbol}`
            });
        },
        fetchData() {
            this.closeSocket()
            _getHomeList(this.symbol).then(data => {
                // console.log(data[0])
                this.quote = data[0]
                this.$nextTick(() => {
                    if (!this.sockets.quote && this.symbol){
                        this.startQuoteScoket()
                    }

                    if (this.tab === '1' && !this.sockets.askBid && this.symbol) {

                        this.startAskBidSocket()
                    }
                })
                // this.startDealsSocket()
            })
        },
        startQuoteScoket() {
            this.sockets.quote = new WebSocket(`${WS_URL}/1/${this.symbol}`)
            this.sockets.quote.onmessage = (evt) => {
                const { data } = evt
                const { code, data: _data } =JSON.parse(data)
                if (code / 1 === 0) {
                    this.quote = _data[0]
                    let str = _data[0] ? _data[0].close.toString() : ''
                    if (str.indexOf('.') != -1) {
                        this.coinLength = str.split('.')[1].length
                    }
                    this.updateKey++
                }
            }
        },
        startAskBidSocket() { // 委托
            this.sockets.askBid = new WebSocket(`${WS_URL}/3/${this.symbol}`)
            this.sockets.askBid.onmessage = (evt) => {
                const { data } = evt
                const { code, data: _data } =JSON.parse(data)
                if (code / 1 === 0) {
                    let { asks, bids } = _data
                    asks = asks.sort((prev, next) => prev.price - next.price)
                    bids = bids.sort((prev, next) => prev.price - next.price)
                    this.asks = asks.slice(0, 17)
                    this.bids = bids.reverse().slice(0, 17)
                }
            }
        },
        startDealsSocket() { // 交易
            this.sockets.deals = new WebSocket(`${WS_URL}/2/${this.symbol}`)
            this.sockets.deals.onmessage = (evt) => {
                const { data } = evt
                const { code, data: _data } =JSON.parse(data)
                if (code / 1 === 0) {
                    this.deals = _data.data.slice(0, 17)
                }
            }
        },
        onRoute(path) { // 跳转汇率页面
            this.$router.push(path)
        },
        onSubmit(direction) { // TODO: 返回
            if (this.tab === '2') {
                this.popType = 'confirm'
                this.direction = direction
                _futrueOrderInit(this.symbol).then(data => {
                    this.initFutrue = data
                    this.show = true
                })
                return
            } else {
                this.$router.push(`/perpetualContract/${this.symbol}`)
            }
        },
        onClose() {
            this.show = false
        },
        handleTimeEnd() {
             _futrueOrderDetail(this.order_no).then(data => {
              clearTimeout(this.timeout)
              this.detailData = data
              if (data.state !== 'created') {
                this.timeout = setTimeout(() => {
                  this.handleTimeEnd()
                }, 1000)
              }
            })
        },
        onOrderConfirm(e) { // 确认订单
            _futrueOrder({...e, symbol: this.symbol, direction: this.direction,session_token: this.initFutrue.session_token}).then(data => {
                // console.log(data)
                this.order_no = data.order_no
                _getBalance().then(data => { // 刷新余额
                    this.$store.commit('user/SET_USERINFO', { balance: data.money})
                })
                 _futrueOrderDetail(data.order_no).then(data => {
                    this.detailData = data
                    this.popType = ''
                })
            }).catch(() => {
                setTimeout(() => {
                    _futrueOrderInit(this.symbol).then(data => {
                        this.order_no = ''
                        this.initFutrue = data
                    })
                }, 1000);                
            })
        },
        closeSocket() {
            this.sockets.quote && this.sockets.quote.close()
            this.sockets.deals && this.sockets.deals.close()
            this.sockets.askBid && this.sockets.askBid.close()
            this.sockets.quote = null
            this.sockets.deals = null
            this.sockets.askBid = null
        },
        onUpdate(symbol) { // 更新
            console.log(symbol)
            this.symbol = symbol;
            this.fetchData()
        },
        OnchangeNight(val){
            this.isNight = val
            eventBus.$emit('onChangeNight', val);
        },
    },
    activated() {
        // if (!this.sockets.quote && this.symbol) {
        //     this.startQuoteScoket()
        // }
        // if (this.tab === '1' && !this.sockets.askBid && this.symbol) {
        //     this.startAskBidSocket()
        // }
        if (!this.symbol) {
            this.symbol = this.$route.params.symbol
            this.fetchData()
            this.closeSocket()
        }
        if (this.tab === '2' && !this.sockets.deals && this.symbol) {
            this.startDealsSocket()
        }
        this.continueOrder()
        this.kineType = this.$route.query.kineType
    },
    deactivated() {
        this.closeSocket()
    },
    beforeDestroy() {
        this.sockets.quote && this.sockets.quote.close()
        this.sockets.deals && this.sockets.deals.close()
        this.sockets.askBid && this.sockets.askBid.close()
        this.sockets.quote = null
        this.sockets.deals = null
        this.sockets.askBid = null
    },
    beforeRouteEnter(to, from, next) {
        const { params: { symbol }} = to
        console.log(symbol)
        next(vm => {
            vm.symbol = symbol
            vm.fetchData()
        })
    }
}
</script>
<style lang="scss" scoped>
@import "../../assets/init.scss";
@keyframes animate1 {
  0% {
    opacity: 1;
    transform: translate3d(100%, 0, 0);
  }
//   40% {
//      opacity: 1;
//     transform: translate3d(50%, 0, 0);
//   }
  100% {
    opacity: 1;
    transform: translate3d(0%, 0, 0);
  }
}
@keyframes animate2 {
    0% {
        opacity: 1;
        transform: translate3d(-100%, 0, 0);
    }

    //   40% {
    //      opacity: 1;
    //     transform: translate3d(50%, 0, 0);
    //   }
    100% {
        opacity: 1;
        transform: translate3d(0%, 0, 0);
    }
}
.slide1 {
  animation: animate1 200ms linear;
}
.slide2 {
    animation: animate2 200ms linear;
}
.tabBtn{
    border: 2px solid #EAEDF2;
    border-radius: 9px;
    color: #868D9A;;
}

.activeBtn{
    background: $btn_main;
    color: #000000;
    border: none;
}
.pb-180{
    ::v-deep .van-tab{
        flex:initial;
        padding: 0 32px;
    }
    ::v-deep .van-tabs__line {
        width: 160px;
    }
}
.buttonSafe{
    bottom: calc(constant(safe-area-inset-bottom));
    bottom: calc(env(safe-area-inset-bottom));
}

.bg-night {
    .tabBtn {
        border: 2px solid #444B58;
    }
    ::v-deep .van-tabs__nav {
        background: $night!important;
    }
    ::v-deep .van-tab--active {
       color: $white;
    }
    ul li{
        background: $night ;
    }
    .activeBtn{
        border: none!important;
    }
}
</style>
